use super::interface::Task;

#[derive(Debug)]
pub enum SelfError {
    EnvError(String),
    SerdeJsonError(serde_json::Error),
    SqlxError(sqlx::Error),
}

impl From<sqlx::Error> for SelfError {
    fn from(err: sqlx::Error) -> Self {
        SelfError::SqlxError(err)
    }
}

impl From<serde_json::Error> for SelfError {
    fn from(err: serde_json::Error) -> Self {
        SelfError::SerdeJsonError(err)
    }
}

impl From<std::env::VarError> for SelfError {
    fn from(err: std::env::VarError) -> Self {
        SelfError::EnvError(format!("Failed to read environment variable: {}", err))
    }
}

// 增加
pub async fn add_task(task: &Task) -> Result<(), SelfError> {
    let url = std::env::var("DATABASE_URL")?;
    let archive_projects = serde_json::to_string(&task.archive_projects)?;
    let pool = sqlx::MySqlPool::connect(&url).await?;
    let sql = r#"INSERT INTO tasks (task_id, task_name, task_time, data_size, status, progress, submit_time, archive_projects)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)"#;
    sqlx::query(sql)
        .bind(&task.task_id)
        .bind(&task.task_name)
        .bind(&task.task_time)
        .bind(&task.data_size)
        .bind(task.status.to_string())
        .bind(&task.progress)
        .bind(&task.submit_time)
        .bind(archive_projects)
        .execute(&pool)
        .await?;
    Ok(())
}

// 查询列表
// pub async fn select_tasks() {}

// 查询任务
pub async fn select_task(task_id: &str) -> Result<Option<Task>, SelfError> {
    let url = std::env::var("DATABASE_URL")?;
    let pool = sqlx::MySqlPool::connect(&url).await?;
    let sql = r#"SELECT * FROM tasks WHERE task_id = ?"#;
    let task = sqlx::query_as::<sqlx::MySql, Task>(sql)
        .bind(task_id)
        .fetch_optional(&pool)
        .await?;
    Ok(task)
}
